import 'dart:convert';

import 'package:dio/dio.dart' as dio;

import 'dart:io';
import 'dart:typed_data';
import 'package:chewie/chewie.dart';
import 'package:crypto/crypto.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:ffmpeg_kit_flutter_min/ffmpeg_kit.dart';
import 'package:ffmpeg_kit_flutter_min/return_code.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:images_picker/images_picker.dart';
import 'package:multi_image_picker_view/multi_image_picker_view.dart';
import 'package:qianyi/controller/homeTabController.dart';
import 'package:qianyi/entity/home/tag_vo_list_entity.dart';
import 'package:qianyi/network/base_entity.dart';
import 'package:qianyi/network/http_entity.dart';
import 'package:qianyi/network/http_manager.dart';
import 'package:qianyi/state/token.dart';
import 'package:qianyi/utils/color_util.dart';
import 'package:qianyi/wcao/kit/index.dart';
import 'package:qianyi/wcao/ui/theme.dart';
import 'package:video_compress_plus/video_compress_plus.dart';
import 'package:video_editor/video_editor.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

import '../../../entity/home/alumb_vo_list.dart';
import '../../../entity/home/category_list_entity.dart';
import '../../../network/http_config.dart';
import '../../../ui/home/VideoView.dart';
import '../../../ui/picker/custom/default_custom_example.dart';
import '../../../ui/picker/custom/files_custom_example.dart';
import '../../../ui/picker/custom/full_custom_example.dart';
import '../../../ui/picker/custom/initial_images_custom_example.dart';
import '../../../ui/picker/custom/selectable_custom_example.dart';
import '../../../ui/picker/picker.dart';
import '../../../ui/video_editor/export_service.dart';
import '../../../utils/DialogUtils.dart';
import 'package:http/http.dart' as http;

class Publish extends StatefulWidget {

  const Publish({Key? key}) : super(key: key);

  @override
  State<Publish> createState() => _PublishState();
}

class _PublishState extends State<Publish> {
  HomeTabController homeTabController = Get.find<HomeTabController>();
  TokenController tokenController = Get.find<TokenController>();
  String cover = '';
  String thumbPath = '';
  int showIndex = 0;
  DateTime? _lastBackPressed;
  List<String> imgsUrl = [];
  String albumId = "";
  String albumName = "";
  String content = "";
  final controller = MultiImagePickerController(
      maxImages: 9,

      picker: (allowMultiple) async {
        return await pickImagesUsingImagePicker(allowMultiple);
      });

  @override
  void initState() {
    // TODO: implement initState

  }

  @override
  void dispose() {
    // TODO: implement dispose

  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          final now = DateTime.now();
          final backButtonPressThreshold = 2; // 两次返回键点击的时间阈值（秒）
          final backButtonDoublePressDelay = 2; // 延迟时间（秒）


          if (_lastBackPressed == null ||
              now.difference(_lastBackPressed!) >
                  Duration(seconds: backButtonPressThreshold)) {
            // 如果两次点击间隔超过阈值，则更新_lastBackPressed为当前时间
            _lastBackPressed = now;
            // 显示提示信息
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('再按一次返回键退出应用')),
            );
            // 返回false，表示不执行返回操作
            return false;
          } else {
            await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
            return true;
          }

          // 如果两次点击间隔小于阈值，则退出应用
        },
        child: Scaffold(
            resizeToAvoidBottomInset: false,
            // extendBodyBehindAppBar: true,

            appBar: AppBar(
              // backgroundColor: Colors.transparent,
              brightness: Brightness.light,

              title: const Text('发布动态'),
              actions: [
                TextButton(
                  onPressed: () async {
                    DialogUtils.showConfirmDialog(
                        context, "是否确认发布", "请确保内容填充完毕").then((
                        result) async {
                      if (result!) {
                        if(homeTabController.selectFQ["twoId"]==null || homeTabController.selectFQ["oneId"]==null) {
                          return ;
                        }

                        if(!homeTabController.addImage.value) {
                          uploadImages();
                        } else {
                          uploadVideo();
                        }
                        // uploadVideo();

                      }
                    }

                    );
                  },
                  child: Obx(()=>homeTabController.isPubshing.value?Text("发布中...", style: TextStyle(
                      color: WcaoTheme.indexBootBarActColor
                  ),):Text("发布", style: TextStyle(
                      color: WcaoTheme.indexBootBarActColor
                  ),))
                  ,
                ),
              ],
            ),
            body: Container(
              height: MediaQuery
                  .of(context)
                  .size
                  .height,
              child: Stack(
                children: [

                  SingleChildScrollView(
                      child: Column(
                        children: [

                          Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Padding(
                                padding: EdgeInsets.only(left: 24),
                                child: TextField(
                                  maxLength: 2000,
                                  minLines: 6,
                                  decoration: InputDecoration(
                                    hintText: '说出你的故事',
                                    border: InputBorder.none,

                                  ),
                                  onEditingComplete: () {

                                  },
                                  onChanged: (e) {
                                    this.content = e;
                                  },
                                  onSubmitted: (e) {},
                                  onTap: () {
                                    // this.addImage = false;
                                    // setState(() {
                                    //
                                    // });
                                  },
                                  maxLines: null,
                                ),


                              ),

                              // 添加图片
                              // Visibility(
                              //   // visible: addImage,
                              //   child:
                              Container(
                                  height: 278,
                                  margin: const EdgeInsets.only(bottom: 24),

                                  child: Obx(() {
                                    return homeTabController.addImage.value
                                        ? FilesCustomExample()
                                        : FullCustomExample();
                                  })
                              ),
                              // ),
                              // 添加话题
                              Container(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 12),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment
                                      .spaceBetween,
                                  children: [
                                    GestureDetector(
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 0),
                                        // decoration: BoxDecoration(
                                        //   color: WcaoTheme.placeholder.withOpacity(.25),
                                        //   borderRadius: BorderRadius.circular(12),
                                        // ),
                                        child: Row(
                                          children: [
                                            Icon(
                                              Icons.tips_and_updates_outlined,
                                              color: WcaoTheme.secondary,
                                            ),
                                            Text("选择标签"),

                                          ],
                                        ),

                                      ),
                                      onTap: () {

                                      },
                                    )
                                    ,
                                    Expanded(
                                      child: Obx(() {
                                        // 设置一个最大长度，超出这个长度将显示省略号
                                        int maxLength = 50; // 你可以根据需要调整这个值
                                        String concatenatedTags = '';
                                        for (TagVo tag in homeTabController
                                            .selectTags) {
                                          if (concatenatedTags.length +
                                              tag.name!.length + 1 >
                                              maxLength) {
                                            // 如果加上当前标签后超出最大长度，则添加省略号并跳出循环
                                            concatenatedTags += '...';
                                            break;
                                          }
                                          concatenatedTags += '#${tag.name!} ';
                                        }

                                        return Center(
                                          child: Text(

                                            concatenatedTags.trim(), // 移除末尾的空格
                                            style: TextStyle(
                                              overflow: TextOverflow.ellipsis,
                                              color: WcaoTheme.primary,
                                            ),
                                          ),
                                        );
                                      }),
                                    ),

                                    IconButton(onPressed: () async {
                                      String uid = await tokenController
                                          .getUid();
                                      IBaseEntity? baseEntity = await HttpManager
                                          .getInstance().request(
                                          url: '/platform/tag/getAllTag?uid=',
                                          method: Method.get);
                                      HttpEntity httpEntity = baseEntity as HttpEntity;
                                      TagVoList list = TagVoList.fromJson(
                                          httpEntity.getOriData()['data']);
                                      showModalBottomSheet(
                                        isScrollControlled: true,
                                        //一：设为true，此时为全屏展示
                                        constraints: BoxConstraints(
                                            maxHeight: MediaQuery
                                                .of(context)
                                                .size
                                                .height - 40),
                                        context: context,
                                        builder: (BuildContext context) {
                                          return Container(
                                              padding: EdgeInsets.all(10),
                                              child: Column(
                                                children: [
                                                  Row(
                                                    mainAxisAlignment: MainAxisAlignment
                                                        .spaceBetween,
                                                    children: [
                                                      Title(
                                                          color: WcaoTheme.base,
                                                          child: Text(
                                                            '编辑标签',
                                                            style: TextStyle(
                                                                fontWeight: FontWeight
                                                                    .w500,
                                                                fontSize: 17),)),
                                                      GestureDetector(
                                                        child: Title(
                                                            color: WcaoTheme
                                                                .base,
                                                            child: Text('完成',
                                                              style: TextStyle(
                                                                  fontWeight: FontWeight
                                                                      .w500,
                                                                  fontSize: 17),)),
                                                        onTap: () {
                                                          Navigator.of(context)
                                                              .pop();
                                                        },
                                                      )

                                                    ],
                                                  ),
                                                  Obx(() =>
                                                      Container(
                                                        width: MediaQuery
                                                            .of(context)
                                                            .size
                                                            .width,
                                                        color: WcaoTheme.primary
                                                            .withOpacity(.01),
                                                        child: Wrap(

                                                          children: buildTagWidgets(),
                                                        ),
                                                      ))
                                                  ,
                                                  TextField(
                                                    decoration: InputDecoration(
                                                      hintText: '请输入标签名',
                                                      border: InputBorder.none,

                                                    ),
                                                    onSubmitted: (value) {
                                                      TagVo t = new TagVo(
                                                          count: "0",
                                                          name: value);
                                                      homeTabController
                                                          .setSelectTags(t);
                                                    },
                                                  ),
                                                  Row(
                                                    children: [

                                                      Title(
                                                          color: WcaoTheme.base,
                                                          child: Text(
                                                            '热门推荐',
                                                            style: TextStyle(
                                                                fontWeight: FontWeight
                                                                    .w500,
                                                                fontSize: 17),)),

                                                    ],
                                                  ),
                                                  Wrap(
                                                    children: list.tagVos!.map((
                                                        item) =>
                                                        TextButton(
                                                          onPressed: () {
                                                            homeTabController
                                                                .setSelectTags(
                                                                item);
                                                          },
                                                          child: Text(
                                                            item.name!,
                                                            style: TextStyle(
                                                                color: WcaoTheme
                                                                    .base
                                                                    .withOpacity(
                                                                    .9),
                                                                fontWeight: FontWeight
                                                                    .w400
                                                            ),),
                                                        )).toList(),
                                                  )
                                                ],
                                              ))
                                          ;
                                        },
                                      );
                                    }, icon: Icon(Icons.arrow_forward_ios))

                                  ],
                                ),
                              ),
                            ],
                          ),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 12),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Icon(Icons.photo_album_outlined,
                                      color: WcaoTheme.secondary,
                                    ),
                                    Text("选择专辑")
                                  ],
                                )
                                ,
                                Text('${albumName}', style: TextStyle(
                                    color: WcaoTheme.primary),),
                                IconButton(
                                    icon: Icon(Icons.arrow_forward_ios),
                                    onPressed: () async {
                                      String uid = await tokenController
                                          .getUid();

                                      IBaseEntity? ibaseEntity = await HttpManager
                                          .getInstance().request(
                                          url: "/platform/album/getAllAlbum?uid=${uid}",
                                          method: Method.get);
                                      HttpEntity httpEntity = ibaseEntity as HttpEntity;
                                      AlbumVoList categoryList = AlbumVoList
                                          .fromJson(
                                          httpEntity.getOriData()['data']);
                                      showModalBottomSheet(
                                        context: context,
                                        builder: (BuildContext context) {
                                          return SafeArea(

                                              child: Container(
                                                  padding: EdgeInsets.all(10),
                                                  // color: Colors.red,
                                                  child: Column(
                                                    children: [
                                                      Row(
                                                        children: [
                                                          Icon(Icons
                                                              .arrow_back_ios),
                                                          Text("用户专辑",
                                                            style: TextStyle(
                                                                fontWeight: FontWeight
                                                                    .w500,
                                                                fontSize: 17),),

                                                        ],

                                                      ),
                                                      Wrap(
                                                        children: categoryList
                                                            .albumVos!.map((
                                                            albumVo) {
                                                          return TextButton(
                                                            onPressed: () {
                                                              this.albumId =
                                                              albumVo.id!;
                                                              this.albumName =
                                                              albumVo.name!;
                                                              setState(() {

                                                              });
                                                              Navigator.pop(
                                                                  context);
                                                            },
                                                            // 这里可以添加您的点击事件处理逻辑
                                                            child: Text(
                                                              "${albumVo.name}",
                                                              style: TextStyle(
                                                                  color: WcaoTheme
                                                                      .base),), // 假设 albumVo 有一个名为 someProperty 的属性
                                                          );
                                                        }).toList(),
                                                      )


                                                    ],
                                                  )
                                              )
                                          );
                                        },
                                      );
                                      ;
                                    })
                              ],
                            ),
                          ),


                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 12),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Icon(Icons.featured_play_list_outlined,
                                      color: WcaoTheme.secondary,
                                    ),
                                    Text("选择分区")
                                  ],
                                )
                                ,
                                Obx(() => Text("${homeTabController
                                    .selectFQ["oneValue"] == null
                                    ? ""
                                    : homeTabController
                                    .selectFQ["oneValue"]}-${homeTabController
                                    .selectFQ["twoValue"] == null
                                    ? ""
                                    : homeTabController.selectFQ["twoValue"]}",
                                  style: TextStyle(color: WcaoTheme.primary),))
                                ,
                                IconButton(
                                    icon: Icon(Icons.arrow_forward_ios),
                                    onPressed: () async {
                                      IBaseEntity? ibaseEntity = await HttpManager
                                          .getInstance().request(
                                          url: "/platform/category/getTreeCategory",
                                          method: Method.get);
                                      HttpEntity httpEntity = ibaseEntity as HttpEntity;
                                      CategoryList categoryList = CategoryList
                                          .fromJson(
                                          httpEntity.getOriData()['data']);
                                      showModalBottomSheet(
                                        context: context,
                                        builder: (BuildContext context) {
                                          return SafeArea(

                                              child: Container(

                                                // color: Colors.red,
                                                child: Row(
                                                  children: [
                                                    Container(
                                                      // width:80,

                                                      // color: Colors.blue,
                                                        child: SingleChildScrollView(
                                                          child: Column(
                                                            children: List
                                                                .generate(
                                                                categoryList
                                                                    .categories!
                                                                    .length, (
                                                                index) {
                                                              return Obx(() {
                                                                final Category e = categoryList
                                                                    .categories![index];
                                                                return Padding(
                                                                  padding: EdgeInsets
                                                                      .all(20),
                                                                  child: GestureDetector(
                                                                    onTap: () {
                                                                      homeTabController
                                                                          .showIndex
                                                                          .value =
                                                                          index;
                                                                      homeTabController
                                                                          .selectFQ["oneId"] =
                                                                      e.id!;
                                                                      homeTabController
                                                                          .selectFQ["oneValue"] =
                                                                      e.name!;
                                                                      homeTabController
                                                                          .selectFQ["twoValue"] =
                                                                      "";
                                                                      homeTabController
                                                                          .selectFQ["twoId"] =
                                                                      "";
                                                                    },
                                                                    child: Text(
                                                                      e.name!,
                                                                      style: TextStyle(
                                                                        fontWeight: FontWeight
                                                                            .w400,
                                                                        color: homeTabController
                                                                            .showIndex
                                                                            .value ==
                                                                            index
                                                                            ? Colors
                                                                            .red
                                                                            : Colors
                                                                            .grey,
                                                                      ),
                                                                    ),
                                                                  ),
                                                                );
                                                              });
                                                            }),
                                                          ),
                                                        )

                                                    ),
                                                    Container(
                                                      width: MediaQuery
                                                          .of(context)
                                                          .size
                                                          .width - 120,

                                                      // color: Colors.pink,
                                                      child: SingleChildScrollView(
                                                        child: Obx(() {
                                                          return Wrap(
                                                            runSpacing: 13,
                                                            spacing: 13,
                                                            children: categoryList
                                                                .categories![homeTabController
                                                                .showIndex
                                                                .value]
                                                                .children!
                                                                .map<Widget>((
                                                                child) =>
                                                                GestureDetector(
                                                                  child: Text(
                                                                      child
                                                                          .name!),
                                                                  onTap: () {
                                                                    homeTabController
                                                                        .selectFQ["twoValue"] =
                                                                    child.name!;
                                                                    homeTabController
                                                                        .selectFQ["twoId"] =
                                                                    child.id!;
                                                                    Navigator
                                                                        .of(
                                                                        context)
                                                                        .pop();
                                                                  },
                                                                ))
                                                                .toList(),
                                                          );
                                                        }),
                                                      ),
                                                    ),

                                                  ],
                                                ),
                                              )
                                          );
                                        },
                                      );
                                      ;
                                    })
                              ],
                            ),
                          ),
                        ],
                      )

                  ),
                  Positioned(child: Column(
                    children: [


                      Container(

                        margin: const EdgeInsets.only(
                            left: 12, right: 12, top: 12),
                        decoration: BoxDecoration(
                          border: Border(
                            top: BorderSide(
                                width: .5,
                                color: WcaoTheme.placeholder.withOpacity(.5)),
                          ),
                        ),
                        child: Row(

                          children: [
                            GestureDetector(

                              onTap: () {
                                homeTabController.addImage.value =
                                !homeTabController.addImage.value;

                                setState(() {});
                              },
                              child: Icon(
                                Icons.image_outlined,
                                color: WcaoTheme.secondary,
                              ),
                            ),
                            IconButton(
                              onPressed: () {},
                              icon: Icon(
                                Icons.location_on_outlined,
                                color: WcaoTheme.secondary,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ), bottom: 3,)
                ],
              ),
            )

        )
    )
    ;
  }

  List<Widget> buildTagWidgets() {
    return homeTabController.selectTags.map((tag) {
      return Container(
        height: 80,
        width: 120,

        // color: WcaoTheme.primary.withOpacity(.3),
        child: Stack(
          children: [
            TextButton(
              onPressed: () {
                // 添加一个实际的回调函数，例如从selectTags中移除当前tag
                // homeTabController.removeTag(tag);
              },
              child: Text(
                tag!.name!,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: WcaoTheme.base.withOpacity(.9),
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
            Positioned(
              top: 0,
              right: 0, // 确保这里的right值正确，以避免图标重叠文本
              child: InkWell( // 使用InkWell来给图标添加点击事件
                onTap: () {
                  // 添加一个实际的回调函数，例如从selectTags中移除当前tag
                  homeTabController.removeTag(tag);
                },
                child: Icon(
                  Icons.close,
                  size: 15,
                  color: WcaoTheme.base.withOpacity(.9), // 为图标设置颜色
                ),
              ),
            ),
          ],
        ),
      );
    }).toList();
  }


  Container selectedImage(String src) {
    return Container(
      margin: const EdgeInsets.only(left: 12),
      child: Stack(
        children: [
          SizedBox(
            width: 68,
            height: 68,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: WcaoUtils.imageCache(src, fit: BoxFit.cover),
            ),
          ),
          Positioned(
            bottom: 0,
            child: Container(
              width: 68,
              height: 24,
              decoration: BoxDecoration(
                borderRadius: const BorderRadius.only(
                    bottomLeft: Radius.circular(8),
                    bottomRight: Radius.circular(8)),
                color: WcaoTheme.base.withOpacity(.5),
              ),
              alignment: Alignment.center,
              child: const Text(
                '删除',
                style: TextStyle(color: Colors.white),
              ),
            ),
          )
        ],
      ),
    );
  }

  Future<void> uploadVideo() async {
    homeTabController.isPubshing.value = true;
    String uid = await tokenController.getUid();
    int  index = 0;

    for (ImageFile item in homeTabController.videoFiles) {

      index++;
      // 使用 File 类来打开文件
      String path = item.path!;

      this.thumbPath = path;
      File oriFile = new File(path);

      MediaInfo? mediaInfo = await VideoCompress.compressVideo(
        path,
        quality: VideoQuality.DefaultQuality,
        deleteOrigin: false,
        includeAudio:true// It's false by default
      );

      int chunkSize = 5 * 1024 * 1024;

      int chunkFileLengthSync = mediaInfo!.filesize!;
      int fileLen = oriFile.lengthSync();
      File? file = chunkFileLengthSync > fileLen?oriFile:mediaInfo.file;
      int fileLength = await file!.length();
      int chunkCount = (fileLength / chunkSize).ceil().toInt();
      if(file!.lengthSync() < chunkSize) {
        Digest fileMd52 = md5.convert(file.readAsBytesSync()!.sublist(0, 5024));
        Map<String, dynamic> params1 = {
          'file': dio.MultipartFile.fromBytes(file.readAsBytesSync()!, filename: '123456.mp4'),
          'fileMd5': fileMd52
        };
        //如果小于5M直接上传
        HttpEntity h8 = await HttpManager.getInstance().request(
            url: '/util/fileoss/uploadOssVideoCover',
            method: Method.file,
            params: params1) as HttpEntity;




        final Uint8List? thumbnail = await VideoThumbnail.thumbnailData(
          video: thumbPath, // 替换为你的视频路径
          imageFormat: ImageFormat.JPEG,
          // maxWidth: 128, // 自定义宽度
          quality: 80, // 缩略图质量，范围0-100
        );
        Digest fileMd521 = md5.convert(thumbnail!.sublist(0, 5024));

        Map<String, dynamic> params2 = {
          'file': dio.MultipartFile.fromBytes(thumbnail!, filename: '12345.png'),
          'fileMd5': fileMd52
        };

        HttpEntity h9 = await HttpManager.getInstance().request(
            url: '/util/fileoss/uploadOssVideoCover',
            method: Method.file,
            params: params2) as HttpEntity;
        this.cover = h9.getOriData()['data'];




        // this.cover = h8.getOriData()['data'];
        this.imgsUrl.add(h8.getOriData()['data']);
        //校验动态，标签，分区都不能为空
        Map<String, dynamic> params = {
          "albumId": this.albumId,
          "categoryId": homeTabController.selectFQ["oneId"],
          "categoryPid": homeTabController.selectFQ["twoId"],
          "content": this.content,
          "count": homeTabController.videoFiles.length,
          "cover": cover,
          "imgsUrl": jsonEncode(this.imgsUrl),
          "status": 1,
          "type": 0,
          "userId": uid,
          "tags": homeTabController.selectTags.value
        };
        // String paramsJson = jsonEncode(params);
        HttpEntity h1 = await HttpManager.getInstance().request(
            url: '/platform/imgDetail/publish',
            params: params,
            method: Method.post) as HttpEntity;
        if(index == homeTabController.videoFiles.length) {
          // this.imgsUrl = [];
          homeTabController.isPubshing.value = false;
          // homeTabController.videoFiles.clear();
          return;
        } else {
          continue;
        }

      }
      String fileNameWithExtension = path
          .split('/')
          .last;
      // String fileName = fileNameWithExtension.split('.').first;
      String _title = fileNameWithExtension;

      Uint8List uint8List = file.readAsBytesSync();
      Digest fileMd5 = md5.convert(
          oriFile.readAsBytesSync().sublist(0, 5024));
      HttpEntity h = await HttpManager.getInstance().request(
          url: "/util/fileoss/upload/checkfile?fileMd5=${fileMd5.toString()}",
          method: Method.get) as HttpEntity;

      String? pathAndUrl = h.getOriData()["data"];
      if (pathAndUrl == null || pathAndUrl!.length == 0 ) {
        for (int i = 0; i < chunkCount; i++) {
          final start = i * chunkSize;
          int end = (i + 1) * chunkSize;
          if (end > uint8List.length) {
            end = uint8List.length; // 如果end超过了文件长度，将其设置为文件长度
          }
          Uint8List chunkBytes = uint8List.sublist(start, end);
          String chunkUri =
              "/video/upload/checkchunk?fileMd5=${fileMd5
              .toString()}&chunk=${i}";
          HttpEntity chunkEnttiy = await HttpManager.getInstance().
          request(url: "/util/fileoss/upload/checkchunk?fileMd5=${fileMd5
              .toString()}&chunk=${i}", method: Method.get) as HttpEntity;
          if (chunkEnttiy.getOriData()['data']) {


            continue;
          };
          //上传分块
          Map<String, dynamic> params = {
            'file': dio.MultipartFile.fromBytes(
                chunkBytes, filename: '12345${i}.png'),
            'fileMd5': fileMd5,
            'chunk': i
          };
          await HttpManager.getInstance().request(
              url: "/util/fileoss/upload/uploadchunkFlutter",
              method: Method.file,
              params: params,
              formData: true

          );
          //如果最后一个分片上传结束合并分片

        }

        //上传封面
        // 创建参数Map
        Map<String, dynamic> params = {
          'fileName': _title,
          "fileMd5": fileMd5.toString(),
          "chunkTotal": chunkCount
        };


        HttpEntity mergeEntity = await HttpManager.getInstance().request(
          url: "/util/fileoss/merge/mergeChunkFlutter",
          method: Method.post,
          params: params,

        ) as HttpEntity;
        String tUrl = mergeEntity.getOriData()['data'];
        this.imgsUrl.add(tUrl);

      } else {
        this.imgsUrl.add(pathAndUrl);
      }
      //分片上传

    }


    final Uint8List? thumbnail = await VideoThumbnail.thumbnailData(
      video: thumbPath, // 替换为你的视频路径
      imageFormat: ImageFormat.JPEG,
      // maxWidth: 128, // 自定义宽度
      quality: 80, // 缩略图质量，范围0-100
    );
    Digest fileMd52 = md5.convert(thumbnail!.sublist(0, 5024));

    Map<String, dynamic> params1 = {
      'file': dio.MultipartFile.fromBytes(thumbnail!, filename: '123123.png'),
      'fileMd5': fileMd52
    };

    HttpEntity h8 = await HttpManager.getInstance().request(
        url: '/util/fileoss/uploadOssVideoCover',
        method: Method.file,
        params: params1) as HttpEntity;
    this.cover = h8.getOriData()['data'];

    //校验动态，标签，分区都不能为空
    Map<String, dynamic> params = {
      "albumId": this.albumId,
      "categoryId": homeTabController.selectFQ["oneId"],
      "categoryPid": homeTabController.selectFQ["twoId"],
      "content": this.content,
      "count": homeTabController.videoFiles.length,
      "cover": cover,
      "imgsUrl": jsonEncode(this.imgsUrl),
      "status": 1,
      "type": 0,
      "userId": uid,
      "tags": homeTabController.selectTags.value
    };
    // String paramsJson = jsonEncode(params);
    HttpEntity h1 = await HttpManager.getInstance().request(
        url: '/platform/imgDetail/publish',
        params: params,
        method: Method.post) as HttpEntity;

    homeTabController.videoFiles.clear();
    homeTabController.isPubshing.value = false;

    print('object');
  }

  Future<void> uploadImages() async {
    homeTabController.isPubshing.value = true;
    Iterable<ImageFile> list = homeTabController.imageController!.images;
    String uid = await tokenController.getUid();
    for (ImageFile item in list) {
      // 使用 File 类来打开文件
      String path = item.path!;
      this.thumbPath = path;
      File oriFile = new File(path);
// 2. compress file and get file.
      var result = await FlutterImageCompress.compressWithFile(
          path, quality: 80);

      String fileNameWithExtension = path
          .split('/')
          .last;
      // String fileName = fileNameWithExtension.split('.').first;
      String _title = fileNameWithExtension;

      Uint8List uint8List = result!;
      Digest fileMd5 = md5.convert(
          oriFile.readAsBytesSync().sublist(1024, 5024));

      // String urlString = "${getBaseUrlMap()[BaseUrl.development]}"+'/api/util/fileoss//upload/checkfile?fileMd5=${fileMd5.toString()}';
      HttpEntity h = await HttpManager.getInstance().request(
          url: "/util/fileoss/upload/checkfile?fileMd5=${fileMd5.toString()}",
          method: Method.get) as HttpEntity;

      String pathAndUrl = h.getOriData()["data"];
      if (pathAndUrl.length == 0) {
        Map<String, dynamic> params1 = {
          'file': dio.MultipartFile.fromBytes(
              uint8List!, filename: '21321321.png'),
          'fileMd5': fileMd5
        };
        HttpEntity h8 = await HttpManager.getInstance().request(
            url: '/util/fileoss/uploadOssVideoCover',
            method: Method.file,
            params: params1) as HttpEntity;
        this.cover = h8.getOriData()['data'];
        this.imgsUrl.add(this.cover);
        //分片上传
      } else {
        this.imgsUrl.add(pathAndUrl);
      }



    }
    //校验动态，标签，分区都不能为空
    Map<String, dynamic> params = {
      "albumId": this.albumId,
      "categoryId": homeTabController.selectFQ["twoId"],
      "categoryPid":  homeTabController.selectFQ["oneId"],
      "content": this.content,
      "count": homeTabController.videoFiles.length,
      "cover": cover,
      "imgsUrl": jsonEncode(this.imgsUrl),
      "status": 1,
      "type": 0,
      "userId": uid,
      "tags": homeTabController.selectTags.value
    };
    // String paramsJson = jsonEncode(params);
    HttpEntity h1 = await HttpManager.getInstance().request(
        url: '/platform/imgDetail/publish',
        params: params,
        method: Method.post) as HttpEntity;
    this.imgsUrl = [];
    homeTabController.isPubshing.value = false;
    homeTabController.selectFQ.clear();
    Get.toNamed("/home");
  }

  contentNotNull() {


  }

}
